package com.server.common.redis.service;

import com.server.common.code.error.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisSmsService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 添加短信验证码
     * @author LXC
     * @date 2023/2/2 16:03
     */
    public void addSmsCode(String redisKey,String mobile, String code,Long timeout,TimeUnit timeUnit){
        redisTemplate.opsForValue().set(redisKey+mobile,code,timeout, timeUnit);
    }

    /**
     * 添加短信验证码
     * @author LXC
     * @date 2023/2/2 16:03
     */
    public void addSmsCode(String redisKey,String mobile, String code){
        redisTemplate.opsForValue().set(redisKey+mobile,code,3*60L, TimeUnit.SECONDS);
    }

    /**
     * 校验短信验证码
     * @author LXC
     * @date 2023/2/2 16:04
     */
    public void checkSmsCode(String redisKey, String mobile, String code){
        if(ObjectUtils.isEmpty(code)){
            throw new BusinessException("短信验证码格式错误");
        }
        String codeNew = redisTemplate.opsForValue().get(redisKey + mobile);

        if(!code.equals(codeNew)){
            throw new BusinessException("短信验证码已失效,请重新获取");
        }

    }

    /**
     * 删除短信验证码
     * @author LXC
     * @date 2023/2/2 16:04
     */
    public void delSmsCode(String redisKey,String mobile){
        redisTemplate.expire(redisKey + mobile,0,TimeUnit.SECONDS);
    }

}
